package com.sanerzone.smscenter.biz.VerifyInterface.util;

import com.sanerzone.common.support.sequence.MsgId;
import com.sanerzone.smscenter.biz.VerifyInterface.data.FilterResult;
import com.sanerzone.smscenter.biz.VerifyInterface.data.Sort;
import com.sanerzone.smscenter.biz.cache.AccountCacheHelper;
import com.sanerzone.smscenter.biz.cache.GatewayCacheHelper;
import com.sanerzone.smscenter.biz.cache.PhoneHelper;
import com.sanerzone.smscenter.biz.cache.WhitelistHelper;
import com.sanerzone.smscenter.biz.entity.SmsGateway;
import com.sanerzone.smscenter.biz.entity.SmsGatewayGroupRel;
import com.sanerzone.smscenter.biz.iface.DataAccess.DataAccess;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSREQMessage;
import com.sanerzone.smscenter.biz.utils.SignHelper;
import com.sanerzone.smscenter.biz.utils.StringHelper;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class MatchUtil {

    /**
     * 查找全国类型的通道
     * @param afterDispOrders
     * @param phone
     * @param smsGatewayGroupRels
     * @param reqMeg
     * @param result
     */
    public static void groupingNationGateway(Map<String,StringBuffer> afterDispOrders,String phone,List<SmsGatewayGroupRel> smsGatewayGroupRels,SMSREQMessage reqMeg,
            List<SMSMTMessage> result){
        boolean isfind=false;
        for(SmsGatewayGroupRel smsGatewayGroupRel:smsGatewayGroupRels){
            String provinceId=smsGatewayGroupRel.getProvinceId();
            String phoneType=smsGatewayGroupRel.getPhoneType();
            String key=phoneType+"_"+provinceId;
            if (isfind){
                break;
            }
            if ("10".equals( provinceId )){
                isfind=true;
                //说明在这个groupid下有全国的通道
                String[] phones=phone.split( "," );
                int offset=0;
                for(int i=0;i<phones.length;i++){
                    String phoneTemp=phones[i];
                    Map<String, String> phoneMap = PhoneHelper.get(phoneTemp);
                    String phoneTypeFind = PhoneHelper.getPhoneType(phoneMap);//运营商
                    if (phoneType.equals( phoneTypeFind )||"QW".equals( phoneType)){
                        StringBuffer sb=afterDispOrders.get(key );
                        if(sb==null){
                            afterDispOrders.put(key,new StringBuffer( phoneTemp )  );
                        }else {
                            sb.append( ","+phoneTemp );
                        }
                        phone=FilterUtil.removePhone(phoneTemp,phone,i-offset  );
                        offset++;
                    }

                }
            }
        }
        if(phone.length()>0){
            //若是分配全国通道后还有这样的手机号，进入待发
            SMSMTMessage entity;

            int length=phone.split( "," ).length;
            String content = reqMeg.getMsgContent();//短信内容
            entity = new SMSMTMessage();
            entity.setSmsREQMessage( reqMeg );
            entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
//            entity.getSmsREQMessage().setMsgContent( "" );
            entity.setId( new MsgId().toString() );//ID
            entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
            entity.setSmsContent( content );//短信内容
            entity.setSmsSize( StringHelper.smsSize( content )*length );//短信长度
            entity.setPhone( phone );
            entity.setSmsContentSign( SignHelper.get(content ) );//短信签名
            entity.setServiceId( reqMeg.getCustomServiceid() ); //默认业务
            entity.setSendStatus( "V006" );
            entity.setBizTime( new Date() );
            entity.setWaitReason( "该手机号码类型无法找到匹配类型通道" );
            entity.setShowLevel( 2 );
            entity.setNeedSplit( 0 );
            entity.setIsEffective( 1 );
            entity.setStatusChangeTime( new Date( ) );
            result.add( entity );

        }

    }

    public static List<Sort> filterLessThanMinNum(List<Sort> sorts,List<SMSMTMessage> result,SMSREQMessage reqMsg){
        Iterator<Sort> sortIterator=sorts.iterator();
        List<StringBuffer> stringBuffers=new ArrayList<>( );
        while (sortIterator.hasNext()){
            Sort sort=sortIterator.next();
            List<SmsGatewayGroupRel> smsGatewayGroupRels=sort.getSmsGatewayGroupRelList();
             Iterator<SmsGatewayGroupRel> iterator=   smsGatewayGroupRels.iterator();
             while (iterator.hasNext()){
                 SmsGatewayGroupRel smsGatewayGroupRel=iterator.next();
                 String code=smsGatewayGroupRel.getGwCode();
                 Integer minNum=GatewayCacheHelper.get( code ).getMinNumber();
                 StringBuffer stringBuffer=sort.getSb();
                 int size=stringBuffer.toString().split( "," ).length;
                 if (minNum==null||minNum>size){
                     iterator.remove();
                 }
             }
             if (sort.getSmsGatewayGroupRelList().size()==0){
                 stringBuffers.add( sort.getSb() );
                 sortIterator.remove();//删除该集合
             }
        }
        if (stringBuffers.size() > 0) {
            StringBuffer finalSb = new StringBuffer();
            for (int i = 0; i < stringBuffers.size(); i++) {
                if (i == 0) {
                    finalSb.append( stringBuffers.get( i ).toString() );
                } else {
                    finalSb.append( "," + stringBuffers.get( i ).toString() );
                }
            }
            //若是分配全国通道后还有这样的手机号，进入待发
            SMSMTMessage entity;
            int length=finalSb.toString().split( "," ).length;
            String content = reqMsg.getMsgContent();//短信内容
            entity = new SMSMTMessage();
            entity.setSmsREQMessage( reqMsg );
            entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
//            entity.getSmsREQMessage().setMsgContent( "" );
            entity.setId( new MsgId().toString() );//ID
            entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
            entity.setSmsContent( content );//短信内容
            entity.setSmsSize( StringHelper.smsSize( content )*length );//短信长度
            entity.setPhone( finalSb.toString() );
            entity.setSmsContentSign( SignHelper.get( content ) );//短信签名
            entity.setServiceId( reqMsg.getCustomServiceid() ); //默认业务
            entity.setSendStatus( "V008" );
            entity.setBizTime( new Date() );
            entity.setWaitReason( "该手机号码类型因小于该group下所查找到所有通道最小发送量而进入待发" );
            entity.setShowLevel( 2 );
            entity.setNeedSplit( 0 );
            entity.setIsEffective( 1 );
            entity.setStatusChangeTime( new Date( ) );
            result.add( entity );

        }
        return sorts;
    }


    /**
     * 过滤不可以发送群发的短信
     * @param afterDispOrders
     *
     * @param groupId
     * @return
     */
    public static List<Sort> filterMassSendOrNot(Map<String,StringBuffer> afterDispOrders,String groupId,List<SMSMTMessage> result,SMSREQMessage reqMsg,DataAccess dataAccess){
                //先整个封装成一个Sort
                Set set = afterDispOrders.keySet();
                Iterator<String> typePidIterator = set.iterator();
                List<Sort> sorts=new ArrayList<>( );
                while (typePidIterator.hasNext()) {
                    String typePid = typePidIterator.next();
                    StringBuffer sb = afterDispOrders.get( typePid );

                    String[] typeAndPid = typePid.split( "_" );
                    String phoneType = typeAndPid[0];
                    String pid = typeAndPid[1];
                    List<SmsGatewayGroupRel> smsGatewayGroupRels1=dataAccess.getGatewayRelListByTypeAndPid(  groupId,phoneType,pid );
                    sorts.add( new Sort(smsGatewayGroupRels1,sb,groupId,phoneType,pid  ) );
                }

                //判断是否可以群发
                for(int i=0;i<sorts.size();i++){
                    Sort sort=sorts.get( i );
                    List<SmsGatewayGroupRel> list=sort.getSmsGatewayGroupRelList();
                    List<SmsGatewayGroupRel> changedList=new ArrayList<>( );
                    Iterator<SmsGatewayGroupRel> iterator=list.iterator();

                    while (iterator.hasNext()){
                        SmsGatewayGroupRel smsGatewayGroupRel= iterator.next();
                        if (sort.getSb().indexOf( "," )!=-1){
                            //说明是群发 则需要判断能
                            String code=smsGatewayGroupRel.getGwCode();
                            //判断这个code是否可以群发
                            Integer flag=GatewayCacheHelper.isSupportMassSend( code );
                            if (flag==null||flag==0){//说明不能群发，就删除掉这个关系
                               iterator.remove();
                            }
                        }else{
                            //说明是单条发送
                            String code=smsGatewayGroupRel.getGwCode();
                            SmsGateway smsGateway=GatewayCacheHelper.get( code );
                            Integer flag=GatewayCacheHelper.isSupportMassSend( code );
                            //如果这个网关是群发网关，而且这个网关最小发送数量大于1
                            Integer minNum=smsGateway.getMinNumber();
                            if (minNum==null){
                                iterator.remove();
                                continue;
                            }
                            if (flag==null||(flag==1&&minNum!=1)){
                                iterator.remove();
                            }
                        }

                    }
                }
                Iterator<Sort> sortIterator= sorts.iterator();
                    while (sortIterator.hasNext()){
                    Sort sort=sortIterator.next();
                    if (sort.getSmsGatewayGroupRelList().size()==0){
                        //说明已经没有网关了   封装进入待发送
                        int length=sort.getSb().toString().split( "," ).length;
                        //若是分配全国通道后还有这样的手机号，进入待发
                        SMSMTMessage entity;
                        String content = reqMsg.getMsgContent();//短信内容
                        entity = new SMSMTMessage();
                        entity.setSmsREQMessage( reqMsg );
                        entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
//                        entity.getSmsREQMessage().setMsgContent( "" );
                        entity.setId( new MsgId().toString() );//ID
                        entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
                        entity.setSmsContent( content );//短信内容
                        entity.setSmsSize( StringHelper.smsSize( content )*length );//短信长度
                        entity.setPhone( sort.getSb().toString() );
                        entity.setSmsContentSign( SignHelper.get(content ) );//短信签名
                        entity.setServiceId( reqMsg.getCustomServiceid() ); //默认业务
                        entity.setSendStatus( "V007" );
                        entity.setBizTime( new Date() );
                        entity.setWaitReason( "该手机号码类型无法找到合适(群发,单发)类型通道" );
                        entity.setShowLevel( 2 );
                        entity.setNeedSplit( 0 );
                        entity.setIsEffective( 1 );
                        entity.setPhoneType( sort.getPhoneType() );
                        entity.setPhoneArea( sort.getArea() );
                        entity.setStatusChangeTime( new Date(  ) );
                        result.add( entity );
                        sortIterator.remove();//删除该集合
                    }
               }


                return sorts;
            }
        public static List<Sort> filterBestPriority(List<Sort> sorts){
            for (Sort sort:sorts){
               List<SmsGatewayGroupRel> smsGatewayGroupRels= sort.getSmsGatewayGroupRelList();
               int maxLevel=0;
               for(SmsGatewayGroupRel smsGatewayGroupRel:smsGatewayGroupRels){
                   int level=smsGatewayGroupRel.getLevel();
                   if (level>maxLevel){
                       maxLevel=level;//取得最大的优先级
                   }
               }
               Iterator<SmsGatewayGroupRel> smsGatewayGroupRelIterator=smsGatewayGroupRels.iterator();
                while (smsGatewayGroupRelIterator.hasNext()){
                    SmsGatewayGroupRel smsGatewayGroupRel= smsGatewayGroupRelIterator.next();
                    if (smsGatewayGroupRel.getLevel()<maxLevel){
                        smsGatewayGroupRelIterator.remove();
                    }

                }

            }
            return sorts;
        }

    /**
     * 权重筛选
     * @param sorts
     * @param result
     * @param reqMsg
     * @return
     */
    public static List<Sort> weightChoose(List<Sort> sorts,List<SMSMTMessage> result,SMSREQMessage reqMsg){
            Random random=new Random( );
            List<Sort> unFindSort=new ArrayList<>( );
            Iterator<Sort> iterator= sorts.iterator();
           while (iterator.hasNext()){
               Sort sort=iterator.next();
               List<SmsGatewayGroupRel> smsGatewayGroupRels=sort.getSmsGatewayGroupRelList();
                List<SmsGatewayGroupRel> randomList=new ArrayList<>();
                for (SmsGatewayGroupRel smsGatewayGroupRel:smsGatewayGroupRels){
                   Integer weight=smsGatewayGroupRel.getWeight();
                   if (weight==null||weight==0){
                       weight=1;//默认等于1
                   }
                    for (int i=0;i<weight;i++){
                        randomList.add( smsGatewayGroupRel );
                    }
               }
                int size=randomList.size();
                int index=random.nextInt(size);//随机找一个
                SmsGatewayGroupRel smsGatewayGroupRel=randomList.get( index );
                SmsGateway smsGateway= GatewayCacheHelper.get( smsGatewayGroupRel.getGwCode() );


                if (smsGateway==null){
                    unFindSort.add( sort );
                    iterator.remove();//删除该条记录
                }else{
                    sort.setSmsGateway( smsGateway );
                }
            }
            //通过网关code未找到网关
            if (unFindSort.size()!=0){
                //有需要进入待发的
                for (int i=0;i<unFindSort.size();i++){
                    Sort sort=unFindSort.get( i );
                    int length=sort.getSb().toString().split( "," ).length;
                    //若是分配全国通道后还有这样的手机号，进入待发
                    SMSMTMessage entity;
                    String content = reqMsg.getMsgContent();//短信内容
                    entity = new SMSMTMessage();
                    entity.setSmsREQMessage( reqMsg );
                    entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
//                    entity.getSmsREQMessage().setMsgContent( "" );
                    entity.setId( new MsgId().toString() );//ID
                    entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
                    entity.setSmsContent( content );//短信内容
                    entity.setSmsSize( StringHelper.smsSize( content )*length );//短信长度
                    entity.setPhone( sort.getSb().toString() );
                    entity.setSmsContentSign( SignHelper.get(content ) );//短信签名
                    entity.setServiceId( reqMsg.getCustomServiceid() ); //默认业务
                    entity.setSendStatus( "V009" );
                    entity.setBizTime( new Date() );
                    entity.setWaitReason( "该网关code"+sort.getSmsGateway().getGwCode()+"未在网关数据库中找到对应网关实体。" );
                    entity.setShowLevel( 2 );
                    entity.setNeedSplit( 0 );
                    entity.setIsEffective( 1 );
                    entity.setStatusChangeTime( new Date() );
                    entity.setPhoneType( sort.getPhoneType() );
                    entity.setPhoneArea( sort.getArea() );
                    result.add( entity );

                }
            }
            return sorts;
    }

    public static FilterResult filterNotSendPhones(String phones,double sendRatio){
        String[] phonesArray=phones.split( "," );
        int size=phonesArray.length;
        int afterCut= (int)(sendRatio*size);
        FilterResult apiResult=new FilterResult();
        if (afterCut==0){
            apiResult.setAfterCutPhones( phones );
            apiResult.setCode( "noNeed" );
            return apiResult;
        }else{
            //这里记录不发的号码
            StringBuffer phonesCuted=new StringBuffer();

            //如果乘以发送比率后的号码数量不是0  就说明需要有号码需要不发
            //需要不发的号码的数量
            int needNotSendNum=size-afterCut;
            int count=0;
            for (int i=0;i<size;i++){
                String phoneTemp=phonesArray[i];
                boolean isInWhiteList=WhitelistHelper.isExist( phoneTemp );
                if (isInWhiteList==false){
                    if (count==0){
                        phonesCuted.append( phoneTemp );
                    }else{
                        phonesCuted.append( ","+ phoneTemp );
                    }
                    //在原来的字符串中剔除这个号码
                    if (i!=size-1){
                        phones=phones.replaceFirst( phoneTemp+",","" );
                    }else{
                        phones=phones.replaceFirst( phoneTemp,"" );
                    }
                    count++;
                    if (count==needNotSendNum){
                        break;
                    }
                }
            }

            apiResult.setAfterCutPhones( phones );
            apiResult.setCutedPhones( phonesCuted.toString() );

            return apiResult;
        }
    }

    public static void sendInBatches(List<Sort> sorts,List<SMSMTMessage> result,SMSREQMessage reqMsg,String groupId){
       //经过分批后的结果
       List<Sort> resultSort=new ArrayList<>();

        for(int i=0;i<sorts.size();i++){
            Sort sort= sorts.get( i );
            SmsGateway smsGateway=sort.getSmsGateway();
            Integer minNum=smsGateway.getMinNumber();
            Integer maxNum=smsGateway.getMaxNumber();
            StringBuffer sb=sort.getSb();
            String sendRadioStr= AccountCacheHelper.getStringValue(reqMsg.getUserid()+"_"+reqMsg.getAccId(), "sendRatio", "1");
            Double sendRadio = null;
            try {
                sendRadio= Double.parseDouble( sendRadioStr );
                if (sendRadio>1.0){
                    sendRadio=1.0;
                }
            }catch (Exception e){
                sendRadio=1.0;
            }
            if (sendRadio!=1.0){
                FilterResult apiResult=null;
                //需要挑选出非白名单号码直接发送成功
                apiResult= filterNotSendPhones( sort.getSb().toString(),sendRadio );
                if (!"noNeed".equals( apiResult.getCode() )) {
                    String phones = apiResult.getAfterCutPhones();
                    sb=new StringBuffer( phones );
                    sort.setSb( sb );
                    String cutedPhones = apiResult.getCutedPhones();

                    int length=(sort.getSb().toString().split( "," ).length );
                    SMSMTMessage entity;
                    String content = reqMsg.getMsgContent();//短信内容
                    entity = new SMSMTMessage();
                    entity.setSmsREQMessage( reqMsg );
                    entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
                    entity.setId( new MsgId().toString() );//ID
                    entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
                    entity.setSmsContent( content );//短信内容
                    entity.setSmsSize( StringHelper.smsSize( content )*length);//短信长度
                    entity.setPhone(cutedPhones );
                    entity.setSmsContentSign( SignHelper.get(content ) );//短信签名
                    entity.setServiceId( reqMsg.getCustomServiceid() ); //默认业务
                    entity.setSendStatus( "S000" );
                    entity.setBizTime( new Date() );
                    entity.setShowLevel( 2 );
                    entity.setNeedSplit( 1 );
                    entity.setIsEffective( 1 );
                    entity.setPhoneType( sort.getPhoneType() );
                    entity.setPhoneArea( sort.getArea() );
                    entity.setSendTime( reqMsg.getSendTime() );
                    entity.setStatusChangeTime( new Date( ) );
                    //设置好网关属性
                    entity.setGatewayId( sort.getSmsGateway().getGwCode() );
                    entity.setGatewayGroup( groupId );
                    entity.setGatewayAppPort( sort.getSmsGateway().getAppCode() );
                    entity.setSubmitTime( new Date(  ) );
                    String exNum="";
                    if (reqMsg.getSendnumber()!=null){
                        exNum=reqMsg.getSendnumber();
                    }
                    smsGatewayForceSign(entity,sort.getSmsGateway());
                    entity.setSpnumber( sort.getSmsGateway().getGwSpNumber() + exNum );
                    result.add( entity );
                }
            }
            String[] phones=sb.toString().split( "," );
            //如果再最大和最小发送区间
            if (phones.length<=maxNum&&phones.length>=minNum){
                resultSort.add( sort );
            }else if (phones.length>=maxNum){
                int numLeft=phones.length;
                int startIndex=0;
                List<String> newBatch=new ArrayList<>( );
                //当还没有发的号码大于通道最大能发送量
                while(numLeft>=maxNum){
                    newBatch.clear();
                   for (int j=startIndex;j<(startIndex+maxNum);j++){
                       newBatch.add( phones[j] );
                   }
                   startIndex+=maxNum;
                    numLeft-=maxNum;
                    String phonesGet=FilterUtil.getPhonesString( newBatch,0,maxNum );
                    Sort sort1=new Sort( );
                    sort1.setSmsGateway( sort.getSmsGateway() );
                    sort1.setSb( new StringBuffer( phonesGet ) );
                    resultSort.add( sort1 );
                }
                if (numLeft>=minNum){
                    newBatch.clear();
                    for (int j=startIndex;j<(startIndex+numLeft);j++){
                        newBatch.add( phones[j] );
                    }
//                    startIndex+=numLeft;
                    String phonesGet=FilterUtil.getPhonesString( newBatch,0,numLeft );
                    Sort sort1=new Sort( );
                    sort1.setSmsGateway( sort.getSmsGateway() );
                    sort1.setSb( new StringBuffer( phonesGet ) );
                    resultSort.add( sort1 );

                }else if (numLeft==0){
                    //什么也不做
                }else {
                    //剩下的进入待处理
                    newBatch.clear();
                    for (int j=startIndex;j<(startIndex+numLeft);j++){
                        newBatch.add( phones[j] );
                    }
                    String phonesGet=FilterUtil.getPhonesString( newBatch,0,numLeft );

                    SMSMTMessage entity;
                    String content = reqMsg.getMsgContent();//短信内容
                    entity = new SMSMTMessage();
                    entity.setSmsREQMessage( reqMsg );
                    entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
//                    entity.getSmsREQMessage().setMsgContent( "" );
                    entity.setId( new MsgId().toString() );//ID
                    entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
                    entity.setSmsContent( content );//短信内容
                    entity.setSmsSize( StringHelper.smsSize( content )*newBatch.size() );//短信长度
                    entity.setPhone(phonesGet );
                    entity.setSmsContentSign( SignHelper.get(content ) );//短信签名
                    entity.setServiceId( reqMsg.getCustomServiceid() ); //默认业务
                    entity.setSendStatus( "D004" );
                    entity.setBizTime( new Date() );
                    entity.setWaitReason( "分批发送后剩余的号码数量小于网关最小发送量" );
                    entity.setShowLevel( 2 );
                    entity.setNeedSplit( 0 );
                    entity.setIsEffective( 1 );
                    entity.setPhoneType( sort.getPhoneType() );
                    entity.setPhoneArea( sort.getArea() );
                    entity.setStatusChangeTime( new Date( ) );
                    //设置好网关属性
                    entity.setGatewayId( sort.getSmsGateway().getGwCode() );
                    entity.setGatewayGroup( groupId );
                    entity.setGatewayAppPort( sort.getSmsGateway().getAppCode() );
                    String exNum="";
                    if (reqMsg.getSendnumber()!=null){
                        exNum=reqMsg.getSendnumber();
                    }
                    entity.setSpnumber( sort.getSmsGateway().getGwSpNumber() + exNum );
                    result.add( entity );
                }
            }else{
                int length=sb.toString().split( "," ).length;
                SMSMTMessage entity;
                String content = reqMsg.getMsgContent();//短信内容
                entity = new SMSMTMessage();
                entity.setSmsREQMessage( reqMsg );
                entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
//                entity.getSmsREQMessage().setMsgContent( "" );
                entity.setId( new MsgId().toString() );//ID
                entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
                entity.setSmsContent( content );//短信内容
                entity.setSmsSize( StringHelper.smsSize( content )*length );//短信长度
                entity.setPhone(sb.toString() );
                entity.setSmsContentSign( SignHelper.get(content ) );//短信签名
                entity.setServiceId( reqMsg.getCustomServiceid() ); //默认业务
                entity.setSendStatus( "D004" );
                entity.setBizTime( new Date() );
                entity.setWaitReason( "小于网关最小发送量" );
                entity.setShowLevel( 2 );
                entity.setNeedSplit( 0 );
                entity.setIsEffective( 1 );
                entity.setPhoneType( sort.getPhoneType() );
                entity.setPhoneArea( sort.getArea() );
                entity.setStatusChangeTime( new Date(  ) );
                //设置好网关属性
                entity.setGatewayId( sort.getSmsGateway().getGwCode() );
                entity.setGatewayGroup( groupId );
                entity.setGatewayAppPort( sort.getSmsGateway().getAppCode() );
                String exNum="";
                if (reqMsg.getSendnumber()!=null){
                    exNum=reqMsg.getSendnumber();
                }
                entity.setSpnumber( sort.getSmsGateway().getGwSpNumber() + exNum);
                result.add( entity );

            }

        }
        Date timeNow=new Date( );
        Date timeSend=reqMsg.getSendTime();
        int resultTime=-1;
        if (timeSend!=null){
            resultTime=timeNow.compareTo( timeSend );
        }

        if (resultTime>=0||timeSend==null){
            //马上发送
            //最后提交分割后的订单
            for (Sort sort:resultSort){
                int length=(sort.getSb().toString().split( "," ).length );
                SMSMTMessage entity;
                String content = reqMsg.getMsgContent();//短信内容
                entity = new SMSMTMessage();
                entity.setSmsREQMessage( reqMsg );
                entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
                entity.setId( new MsgId().toString() );//ID
                entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
                entity.setSmsContent( content );//短信内容
                entity.setSmsSize( StringHelper.smsSize( content )*length);//短信长度
                entity.setPhone(sort.getSb().toString() );
                entity.setSmsContentSign( SignHelper.get(content ) );//短信签名
                entity.setServiceId( reqMsg.getCustomServiceid() ); //默认业务
                entity.setSendStatus( "T000" );
                entity.setBizTime( new Date() );
                entity.setShowLevel( 2 );
                entity.setNeedSplit( 1 );
                entity.setIsEffective( 1 );
                entity.setPhoneType( sort.getPhoneType() );
                entity.setPhoneArea( sort.getArea() );
                entity.setSendTime( reqMsg.getSendTime() );
                entity.setStatusChangeTime( new Date( ) );

                //设置好网关属性
                entity.setGatewayId( sort.getSmsGateway().getGwCode() );
                entity.setGatewayGroup( groupId );
                entity.setGatewayAppPort( sort.getSmsGateway().getAppCode() );
                entity.setSubmitTime( new Date(  ) );
                String exNum="";
                if (reqMsg.getSendnumber()!=null){
                    exNum=reqMsg.getSendnumber();
                }
                smsGatewayForceSign(entity,sort.getSmsGateway());
                entity.setSpnumber( sort.getSmsGateway().getGwSpNumber() + exNum );
                result.add( entity );
            }

        }else{
            for (Sort sort:resultSort){
                SMSMTMessage entity;
                int length=sort.getSb().toString().split( "," ).length;
                String content = reqMsg.getMsgContent();//短信内容
                entity = new SMSMTMessage();
                entity.setSmsREQMessage( reqMsg );
                entity.getSmsREQMessage().setPhones( "" );//把req的phones设置成空串
                entity.setId( new MsgId().toString() );//ID
                entity.setContentType( "0" );//内容类型 默认 0   0是什么意思？
                entity.setSmsContent( content );//短信内容
                entity.setSmsSize( StringHelper.smsSize( content )*length );//短信长度
                entity.setPhone(sort.getSb().toString() );
                entity.setSmsContentSign( SignHelper.get(content ) );//短信签名
                entity.setServiceId( reqMsg.getCustomServiceid() ); //默认业务
                entity.setSendStatus( "W000" );
                entity.setBizTime( new Date() );
                entity.setShowLevel( 2 );
                entity.setNeedSplit( 0 );//不需要分割
                entity.setIsEffective( 1 );
                entity.setSendTime( reqMsg.getSendTime() );
                entity.setPhoneType( sort.getPhoneType() );
                entity.setPhoneArea( sort.getArea() );
                entity.setStatusChangeTime( new Date( ) );
                //设置好网关属性
                entity.setGatewayId( sort.getSmsGateway().getGwCode() );
                entity.setGatewayGroup( groupId );
                entity.setGatewayAppPort( sort.getSmsGateway().getAppCode() );
                String exNum="";
                if (reqMsg.getSendnumber()!=null){
                    exNum=reqMsg.getSendnumber();
                }
                entity.setSpnumber( sort.getSmsGateway().getGwSpNumber() + exNum );
                //网关强制签名
                smsGatewayForceSign(entity,sort.getSmsGateway());
                result.add( entity );
            }

        }
    }

    public static void reSortsByWhiteList(List<Sort> sorts){
        //根据白名单再排序
        for (int i=0;i<sorts.size();i++){
            Sort sort=sorts.get( i );
            StringBuffer sb = sort.getSb();
            String[] phones= sb.toString().split( "," );
            String phone=sb.toString();
            List<String> phoneReplace=new ArrayList<>();
            for (int j=0;j<phones.length;j++){
                String pTemp= phones[j];
                boolean isExsit=WhitelistHelper.isExist( pTemp );
                if (isExsit){
                    if (j!=0){
                        phone=phone.replaceFirst( ","+pTemp,"" );
                        phoneReplace.add( pTemp );
                    }
                }
            }
            StringBuffer sbNew=new StringBuffer(phone);
            for (int j=0;j<phoneReplace.size();j++){
                String phoneT= phoneReplace.get( j );
                sbNew.insert( 0,phoneT+"," );

            }
            sort.setSb( sbNew );


        }
    }

    public static void smsGatewayForceSign(SMSMTMessage smsmtMessage,SmsGateway smsGateway){
        if ("1".equals( smsGateway.getNeedSign() )){
            String content=smsmtMessage.getSmsContent();
            String sign=getSign( content );
            String signContent=smsGateway.getSignContent();
            if (StringUtils.isNotBlank( signContent )){
                content=content.replaceFirst( "【"+sign+"】","【"+smsGateway.getSignContent()+"】" );
                smsmtMessage.setSmsContent( content );
            }

        }



    }


    private static String getSign(String content){
        return SignHelper.get(content);
    }


}



